package com.example.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ZKServiceImpl implements ZKService {

    @Resource
    private CuratorFramework curatorFramework;

    /****
     *
     * 创建节点
     * 
     * @param mode
     * @param ttl
     * @param path
     * @throws Exception
     */
    @Override
    public void createNode(CreateMode mode, int ttl, String path) throws Exception {
        this.curatorFramework.create().withTtl(ttl).creatingParentsIfNeeded().withMode(mode).forPath(path);
    }

    /****
     *
     * 监听节点的创建
     * 
     * @param path
     * @param pathChildrenCacheListener
     * @throws Exception
     */
    @Override
    public void watchNode(String path, PathChildrenCacheListener pathChildrenCacheListener) throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework, path, true);
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
    }

    @Override
    public CuratorFramework getCuratorFramework() {
        return this.curatorFramework;
    }
}
